package com.pigotech.ptwo.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by ghb on 2018/3/16.
 */

public class UtilMd5 {
    /**
     *  获取16位MD5
     * @param plainText
     * @return
     */
    public static String getMd516(String plainText) {
        return getMd516(plainText.getBytes());
    }

    /**
     *  获取16位MD5
     * @param bytes
     * @return
     */
    public static String getMd516(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);

            int n = 0;
            byte b[] = md.digest();
            int length = b.length;
            StringBuffer buf = new StringBuffer("");
            for (int i = 0; i < length; i++) {
                n = b[i];
                if (n < 0)
                    n += 256;
                if (n < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(n));
            }
            return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 32位MD5加密
     * @param plainText
     * @return
     */
    public static String getMd532(String plainText) {
        return getMd532(plainText.getBytes());
    }

    /**
     * 32位MD5加密
     * @param bytes
     * @return
     */
    public static String getMd532(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);

            int n = 0;
            byte b[] = md.digest();
            int length = b.length;
            StringBuffer buf = new StringBuffer("");
            for (int i = 0; i < length; i++) {
                n = b[i];
                if (n < 0)
                    n += 256;
                if (n < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(n));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }
}
